package com.adobe.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.system.ApplicationDomain;
	import flash.text.TextField;
	import flash.utils.getQualifiedClassName;
	
	/**
	 * 클래스 유틸.
	 * @author kssuman
	 */
	public class ClassUtil
	{
		/**
		 * 클래스 존재 여부.
		 * @param	str_class	클래스명.
		 * @return				boolean값.
		 */
		static public function hasClass(str_class:String):Boolean
		{
			return ApplicationDomain.currentDomain.hasDefinition(str_class);
		}
		
		
		
		static public function getClassName(obj:Object):String {
			var className:String = getQualifiedClassName(obj);
			return className.slice(className.lastIndexOf("::") + 2);
		}
		
		
		
		/**
		 * 클래스를 인스턴스로 생성.
		 * @param	str_class	클래스명.
		 * @return				인스턴스.
		 */
		static public function createInstance(str_class:String):*
		{
			// get class
			var css:Class;
			if ( hasClass(str_class) )
			{
				css = Class(ApplicationDomain.currentDomain.getDefinition(str_class));
				
				// create instance of getted class
				return new css();
			}
			
			var sp:Sprite = new Sprite();
			sp.graphics.lineStyle(0.25, 0xFF0000);
			sp.graphics.beginFill(0xFFFFFF);
			sp.graphics.drawRect(0, 0, 30, 30);
			sp.graphics.moveTo(0, 0);
			sp.graphics.lineTo(30, 30);
			sp.graphics.moveTo(30, 0);
			sp.graphics.lineTo(0, 30);
			sp.graphics.endFill();
			
			return sp;
		}
		
		/**
		 * 클래스 생성.
		 * @param	str_class		클래스명.
		 * @return					클래스.
		 */
		static public function createClass(str_class:String):Class
		{
			return Class(ApplicationDomain.currentDomain.getDefinition(str_class));
		}
		
		/**
		 * 인스턴스를 제거.
		 * @param	obj			제거할 인스턴스.
		 */
		static public function removeInstance(obj:*):void
		{
			var numChild:int;
			var i:int;
			
			if ( obj.hasOwnProperty("numChildren") )
			{
				numChild = obj.numChildren;
			}
			else
			{
				numChild = 0;
			}
			
			i = 0;
			for(i = (numChild - 1); i >= 0; i--)
			{
				var objTmp:* = obj.getChildAt(i);
				if ( objTmp.hasOwnProperty("destroyObject") )
				{
					objTmp.destroyObject();
					obj.removeChildAt(i);
				}
				else if (objTmp is Sprite)
				{
					removeInstance(objTmp);
					objTmp.graphics.clear();
					obj.removeChildAt(i);
				}
				else if(objTmp is TextField)
				{
					objTmp.text = "";
					obj.removeChildAt(i);
				}
				else if(objTmp is SimpleButton)
				{
					obj.removeChildAt(i);
				}
				else if(objTmp is Shape)
				{
					objTmp.graphics.clear();
					obj.removeChildAt(i);
				}
				else if(objTmp is Bitmap)
				{
					removeInstance(objTmp);
					objTmp.bitmapData.dispose();
					objTmp.bitmapData = null;
					obj.removeChildAt(i);
				}
				else if(objTmp is BitmapData)
				{
					objTmp.dispose();
					obj.removeChildAt(i);
				}
				else
				{
					obj.removeChildAt(i);
				}
			}
		}
	}
}